package com.excesys.exsecs.eco.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.excesys.exsecs.eco.entity.EcoCoolHourFlow;
import com.excesys.exsecs.eco.entity.EcoPowerHourFlow;
import com.excesys.exsecs.eco.mapper.EcoCoolHourFlowMapper;
import com.excesys.exsecs.eco.mapper.EcoPowerHourFlowMapper;
import com.excesys.exsecs.eco.service.EcoPowerHourFlowService;
import lombok.RequiredArgsConstructor;
import org.checkerframework.checker.units.qual.A;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 节能用电量小时表
 *
 * @author lxc
 * @date 2024-11-26 13:30:39
 */
@Service
@RequiredArgsConstructor
public class EcoPowerHourFlowServiceImpl extends ServiceImpl<EcoPowerHourFlowMapper, EcoPowerHourFlow> implements EcoPowerHourFlowService {

    private final EcoPowerHourFlowMapper powerHourFlowMapper;
    private final EcoCoolHourFlowMapper coolHourFlowMapper;

    @Override
    public double getSumTotalPower(String date) {
        return powerHourFlowMapper.getSumTotalPower(date);
    }

    @Override
    public List<Map<String, Object>> chartPower(String startTime, String endTime) {
        return powerHourFlowMapper.chartPower(startTime, endTime);
    }


    /**
     * 总/平均用电量、冷量、COP
     *
     * @param startTime
     * @param endTime
     * @return
     */

    public JSONObject getTotal(String startTime, String endTime) {
        JSONObject result = new JSONObject();
        Double totalPower = (double) 0;
        Double totalCool = (double) 0;

        //总用电量
        QueryWrapper<EcoPowerHourFlow> qw = new QueryWrapper<>();
        qw.select("SUM(incr_value) AS totalPower");
        if (StringUtils.isNotEmpty(startTime) && StringUtils.isNotEmpty(endTime)) {
            qw.between("time_value", startTime, endTime);
        }
        List<Map<String, Object>> sumList = powerHourFlowMapper.selectMaps(qw);
        if (ObjectUtil.isNotNull(totalPower)) {
            totalPower = Convert.convert(Double.class, sumList.get(0).get("totalPower"));
        }
        //平均逐时用电量
        Date date1 = DateUtil.parse(startTime);
        Date date2 = DateUtil.parse(endTime);
        long intervalhours = DateUtil.between(date1, date2, DateUnit.HOUR);
        DecimalFormat decimalFormat = new DecimalFormat("#.00");
        String avgHourPower = decimalFormat.format(totalPower / intervalhours);
        //总冷量
        QueryWrapper<EcoCoolHourFlow> qwc = new QueryWrapper<>();
        qwc.select("SUM(incr_value) AS totalCool");
        if (StringUtils.isNotEmpty(startTime) && StringUtils.isNotEmpty(endTime)) {
            qwc.between("time_value", startTime, endTime);
        }
        List<Map<String, Object>> coolList = coolHourFlowMapper.selectMaps(qwc);
        if (ObjectUtil.isNotNull(coolList)) {
            totalCool = Convert.convert(Double.class, coolList.get(0).get("totalCool"));
        }
        //平均逐时用冷量
        String avgHourCool = decimalFormat.format(totalCool / intervalhours);
        //综合COP
        DecimalFormat copFormat = new DecimalFormat("#");
        String cop = copFormat.format(totalCool / totalPower);

        result.set("totalPower", totalPower);
        result.set("avgHourPower", avgHourPower);
        result.set("totalCool", totalCool);
        result.set("avgHourCool", avgHourCool);
        result.set("cop", cop);

        return result;
    }


    @Override
    public JSONObject getTotal2(String startTime, String endTime) {
        JSONObject result = new JSONObject();
        //总用电量、总冷量、平均逐时用电量、平均逐时用冷量、cop
        QueryWrapper<EcoCoolHourFlow> qw = new QueryWrapper<>();
        qw.select("SUM( power_incr_value ) AS totalPower,\n" +
                "\tSUM( incr_value ) AS totalCool,\n" +
                "\tFORMAT( AVG( power_incr_value ), 2 ) AS avgHourPower,\n" +
                "\tFORMAT( AVG( incr_value ), 2 ) AS avgHourCool,\n" +
                "\tFORMAT(AVG(cop),2) AS cop ");
        if (StringUtils.isNotEmpty(startTime) && StringUtils.isNotEmpty(endTime)) {
            qw.between("time_value", startTime, endTime);
        }
        List<Map<String, Object>> mapList = coolHourFlowMapper.selectMaps(qw);
        result.append("top", mapList.get(0));
        //系统逐时用电量、制冷量、cop
        QueryWrapper<EcoCoolHourFlow> qwList = new QueryWrapper<>();
        qwList.select("time_value AS timeValue,\n" +
                "\tcop,\n" +
                "\tincr_value AS coolValue,\n" +
                "\tpower_incr_value AS powerValue");
        if (StringUtils.isNotEmpty(startTime) && StringUtils.isNotEmpty(endTime)) {
            qwList.between("time_value", startTime, endTime);
        }
        List<Map<String, Object>> avgHourList = coolHourFlowMapper.selectMaps(qwList);
        result.append("list", avgHourList);
        return result;
    }

    /**
     * 节能系统 能耗查询
     *
     * @param startTime
     * @param endTime
     * @return
     */
    public JSONObject energyQuery2(String startTime, String endTime) {
        JSONObject result = new JSONObject();

        Map params = new HashMap<>();
        params.put("startTime", startTime);
        params.put("endTime", endTime);
        if (startTime.length() >= 10) {
            params.put("dateFormat", "%Y-%m-%d");
        } else if (startTime.length() >= 7) {
            params.put("dateFormat", "%Y-%m");
        } else {
            params.put("dateFormat", "%Y");
        }
        List<String> devNames = Arrays.asList("", "主机", "泵", "塔");
        List<String> engNames = Arrays.asList("sum", "zhuji", "beng", "ta");
        List sumList = new ArrayList<>();
        for (int i = 0; i < devNames.size(); i++) {
            Double sum = (double) 0;
            params.put("devName", devNames.get(i));
            List<Map> mapList = powerHourFlowMapper.qurryEnergy(params);
            for (int j = 0; j < mapList.size(); j++) {
                Double value = Convert.convert(Double.class, mapList.get(j).get("sumValue"));
                sum += value;
            }
            sumList.add(sum);
            result.set(engNames.get(i), mapList);
        }
        result.set("sumList", sumList);
        return result;
    }

    /**
     * 能耗计量
     *
     * @param startTime
     * @param endTime
     * @return
     */
    @Override
    public List energyMeasure(String startTime, String endTime) {
        List resultList = new ArrayList<>();

        String newStartTime = startTime;
        String newEndTime = endTime;

        String dateFormat = "";
        if (startTime.length() >= 10) {
            dateFormat = "%Y-%m-%d";
        } else if (startTime.length() >= 7) {
            dateFormat = "%Y-%m";
            newStartTime += "-01";
            newEndTime += "-28";
        } else {
            dateFormat = "%Y";
            newStartTime += "-01-01";
            newEndTime += "-12-31";
        }
        //日期集合
        List<String> dateList = powerHourFlowMapper.dateRange(dateFormat, newStartTime, newEndTime);
        //设备集合 {'a1':'1#'}
        //Map<String,String> devMap = new HashMap<>();

        //List<Map> devsAndunits = powerHourFlowMapper.selectDevNames();
        //for (int i = 0; i < devsAndunits.size(); i++) {
        //devMap.put("a"+(i),String.valueOf(devsAndunits.get(i).get("deviceName")));
        //}

        for (int i = 0; i < dateList.size(); i++) {
            Map params = new HashMap<>();
            params.put("timeValue", dateList.get(i));
            params.put("dateFormat", dateFormat);
            List<Map> itemList = powerHourFlowMapper.qurryEnergy(params);

            Map devHost = new HashMap<>();

            for (int j = 0; j < itemList.size(); j++) {
                devHost.put("date", itemList.get(j).get("dateFormat"));
                devHost.put(itemList.get(j).get("deviceName"), itemList.get(j).get("sumValue"));
            }
            resultList.add(devHost);

        }

        return resultList;
    }


    @Override
    public List energyQuery(String startTime, String endTime) {
        List resultList = new ArrayList<>();

        String newStartTime = startTime;
        String newEndTime = endTime;


        String dateFormat = "";
        if (startTime.length() >= 10) {
            dateFormat = "%Y-%m-%d";
        } else if (startTime.length() >= 7) {
            dateFormat = "%Y-%m";
            newStartTime += "-01";
            newEndTime += "-30";
        } else {
            dateFormat = "%Y";
            newStartTime += "-01-01";
            newEndTime += "-12-31";
        }
        //日期集合
        List<String> dateList = powerHourFlowMapper.dateRange(dateFormat, newStartTime, newEndTime);
        //设备集合 {'a1':'1#'}
        Map<String, String> devMap = new HashMap<>();

//		List<Map> devsAndunits = powerHourFlowMapper.selectDevNames();
//		for (int i = 0; i < devsAndunits.size(); i++) {
//			devMap.put("a"+(i),String.valueOf(devsAndunits.get(i).get("deviceName")));
//		}

        for (int i = 0; i < dateList.size(); i++) {
            Map params = new HashMap<>();
            params.put("timeValue", dateList.get(i));
            params.put("dateFormat", dateFormat);
            List<Map> itemList = powerHourFlowMapper.qurryEnergy(params);

            Map devHost = new HashMap<>();
            Double hostVal = (double) 0;
            Double pumpVal = (double) 0;
            Double towerVal = (double) 0;
            Double totalVal = (double) 0;

            for (int j = 0; j < itemList.size(); j++) {

//				devHost.put(itemList.get(j).get("deviceName"),itemList.get(j).get("sumValue"));
                Double itemVal = Convert.convert(Double.class, itemList.get(j).get("sumValue"));
                if (itemList.get(j).get("deviceName").toString().contains("主机")) {
                    devHost.put("date", itemList.get(j).get("dateFormat"));
                    hostVal += itemVal;
                } else if (itemList.get(j).get("deviceName").toString().contains("泵")) {
                    pumpVal += itemVal;
                } else {
                    towerVal += itemVal;
                }
            }
            totalVal = hostVal + pumpVal + towerVal;
            devHost.put("totalVal", String.format("%.2f", totalVal));
            devHost.put("hostVal", String.format("%.2f", hostVal));
            devHost.put("pumpVal", String.format("%.2f", pumpVal));
            devHost.put("towerVal", String.format("%.2f", towerVal));

            resultList.add(devHost);

        }

        return resultList;
    }

    @Override
    public List<Map<String, Object>> getElectricalEnergyList(String startDate, String endDate, List<String> idList) {
        List<Map<String, Object>> list = new ArrayList<>();
        if (startDate.matches("\\d{4}-\\d{2}-\\d{2}") && endDate.matches("\\d{4}-\\d{2}-\\d{2}")) {
            list = this.baseMapper.electricalEnergyListByDay(startDate + " 00", endDate + " 01", idList);
        }
        if (startDate.matches("^\\d{4}-(0[1-9]|1[0-2])$") && endDate.matches("^\\d{4}-(0[1-9]|1[0-2])$")) {
            list = this.baseMapper.electricalEnergyListByMonth(startDate.replace("-", ""), endDate.replace("-", ""), idList);
        }
        if (startDate.matches("^\\d{4}$") && endDate.matches("^\\d{4}$")) {
            list = this.baseMapper.electricalEnergyListByYear(startDate, endDate, idList);
        }
        return list;
    }


}